'use strict';
const querystring = require("querystring");

module.exports = (request, response, rfun)=>{
    const pubfun = require("../pubfun"), item = require("./itemcolor.json");
    let dv = '[]';
    switch(request.GET.pathname){
        case "/ajax/menu":{
			dv = [
                {"icon":"el-icon-setting","index":"4","title":"设置","list":[
                    {"name":"刷新脚本","path":"reloadscript","comp":"syscript","col":{}},
                    {"name":"发送邮件","path":"sendmail","comp":"symail","col":{}}
                ]},
                {"icon":"el-icon-document","index":"5","title":"用户信息","list":[
                    {"name":"注册玩家","path":"user","col":{"0":"UserID","1":"账号","2":"昵称","3":"注册时间","4":"注册IP"}},
                    {"name":"玩家明细","path":"userdetail","comp":"searchuser","col":{}},
                    {"name":"在线玩家","path":"online","col":{"0":"UserID","1":"登录时间"}},
                    {"name":"登录日志","path":"loginlog","col":{"0":"UserID","1":"登录时间","2":"游戏类型","3":"密码","4":"登录IP","5":"渠道ID","6":"机器码"}},
                    {"name":"道具日志","path":"baglog","comp":"searchitem","col":{"0":"UserID","1":"时间","2":"道具ID","3":"改变数量","4":"新数量","5":"原因","6":"其它"}},
                    {"name":"邮件列表","path":"mails","col":{"0":"邮件ID","1":"发送用户","2":"接受用户","3":"标题","4":"道具","5":"领取时间","6":"内容"}},
                    {"name":"挑战关卡","path":"chapter","col":{"0":"UserID","1":"关卡ID","2":"关卡名称","3":"类型(1大厅2好友)","4":"创建时间","5":"挑战支付","6":"次数","7":"步数","8":"开始次数","9":"成功次数","10":"完成次数"}}
                ]},
                {"icon":"el-icon-goods","index":"7","title":"充值信息","list":[
                    {"name":"充值汇总","path":"pay","col":{"0":"账号","1":"支付金额"}}
                ]},
                {"icon":"el-icon-edit","index":"8","title":"系统设置","list":[
                    {"name":"设置密码","path":"sysetpass","col":{}}
                ]}
            ];
			break;
        }case "/ajax/user":{
			getData(request.GET.query, "SELECT userid,account,nickname,regtime::text,loginip FROM users", "regtime", rfun, "DB", true);
			return;
        }case "/ajax/userdetail":{ //玩家明细
            if(!request.GET.query.V) break;
			pubfun.DB.query("SELECT B.*,nickname,regtime::text FROM users A LEFT JOIN games B ON A.userid=B.userid where A.userid = $1 AND B.tp = 1", (rs)=>{
                dv = {view:""};
                if(!rs.rows[0]){
                    dv.view = "没有数据";
                    return rfun(dv);
                }
                dv.view = rs.rows[0][6] + " " + rs.rows[0][7] + "\n"
                let gm = rs.rows[0][2];
                dv.view += "\n最后领取体力时间:" + new Date(gm.powerlast).toLocaleString();
                dv.view += "\n宝箱数量:" + gm.boxnum;
                dv.view += "\n关卡:";
                for(let i = 1;gm.chapter && i < gm.chapter.length;i++){
                    if(gm.chapter[i]) dv.view += "\n  " + i + " 时间 " + gm.chapter[i][0] + " 步数 " + gm.chapter[i][1];
                }
                dv.view += "\n图鉴:";
                for(let k in gm.color){
                    dv.view += "\n  " + k + ":" + gm.color[k] + "(" + item[gm.color[k]].name + ")";
                }
                dv.view += "\n挑战关卡:";
                if(gm.run){
                    dv.view += "\n  " + gm.run.n + "[" + gm.run.id + "] 创建用户ID" + gm.run.userid + " 挑战时间:" + new Date(gm.run.t).toLocaleString() + " 支付钻石:" + gm.run.pay + " 步数:" + gm.run.v;
                }
                gm = rs.rows[0][3];
                dv.view += "\n背包:";
                for(let k in gm){
                    dv.view += "\n  " + (item[k]?item[k].name:"") + "(" + k + "):" + gm[k];
                }
                gm = rs.rows[0][4];
                dv.view += "\n宝箱:";
                for(let i = 0;i < gm.length;i++){
                    if(gm[i]) dv.view += "\n  " + (item[gm[i][0]]?item[gm[i][0]].name:"") + "(" + gm[i][0] + ") 放入时间 " + new Date(gm[i][1]).toLocaleString();
                }
                gm = rs.rows[0][5];
                dv.view += "\n任务: 最后操作时间" + new Date(gm.lt).toLocaleString();
                dv.view += "\n  成就任务:";
                for(let k in gm[0]){
                    dv.view += "\n    " + k + ":" + gm[0][k];
                }
                dv.view += "\n  日常任务:";
                for(let k in gm[1]){
                    dv.view += "\n    " + k + ":" + gm[1][k];
                }
                if(gm[2]){
                    dv.view += "\n  每天连续任务:";
                    for(let k in gm[2]){
                        dv.view += "\n    " + k + ":" + gm[2][k];
                    }
                }
                dv.view += "\n  已经领奖任务:";
                for(let k in gm.rw){
                    dv.view += "\n    " + k;
                }
                dv.view += "\n  活跃度领取:";
                if(gm.active){
                    for(let k in gm.active){
                        dv.view += "\n    " + k;
                    }
                }
                dv.view += "\n  签到:";
                if(gm.d7t) dv.view += "\n    签到天数:" + gm.d7 + " 最后签到时间:" + new Date(gm.d7t).toLocaleString();
                dv.view += "\n  转盘:";
                if(gm.zp) dv.view += "\n    最后领取时间:" + new Date(gm.zp).toLocaleString();
                rfun(dv);
            },[request.GET.query.V],true)
			return;
        }case "/ajax/online":{
            pubfun.RS(0).HGETALL("ONLINE:1", (err, rep)=>{
                if(err){
                    request.LOG.error(err);
                    return;
                }
                dv = [];
                for(let k in rep){
                    dv.push([k, new Date(Number(rep[k])).toLocaleString()]);
                }
                rfun(dv);
            })
			return;
        }case "/ajax/loginlog":{
            getData(request.GET.query, "SELECT userid,logtime::text,gametp,password,loginip,channelid,macnum FROM loginlog", "logtime", rfun);
            return;
        }case "/ajax/baglog":{
            getData(request.GET.query, "SELECT userid,logtime::text,itemid,changenum,newnum,reason,ext FROM baglog", "logtime", (dv)=>{
                const itemc = require("./item");
                for(let i=0;i<dv.data.length;i++){
                    if(dv.data[i][2] in item) dv.data[i][2] = item[dv.data[i][2]].name + "(" + dv.data[i][2] + ")";  
                    if(dv.data[i][5] in itemc.reason) dv.data[i][5] = itemc.reason[dv.data[i][5]] + "(" + dv.data[i][5] + ")"; 
                }
                rfun(dv);
            });
            return;
        }case "/ajax/mails":{
            getData(request.GET.query, "SELECT mid,sendid,touserid,title,ext,gettime::text,body FROM mails", "mid", (dv)=>{
                for(let i=0;i<dv.data.length;i++){
                    if(dv.data[i][4]) dv.data[i][4] = JSON.stringify(dv.data[i][4]);  
                }
                rfun(dv);
            },true);
            return;
        }case "/ajax/pay":{
			dv = [["user", "100"]];
			break;
		}case "/ajax/reloadscript":{
			getGameHttp(request.GET.query.V, (str)=>{
                rfun({view:str}); 
            });
			return;
		}case "/ajax/sendmail":{
            if(isNaN(request.GET.query.V)) request.GET.query.V = 0;
            try{
                let ext = JSON.parse(request.GET.query.E3);
                if(!Array.isArray(ext)){
                    rfun({view:"发送失败-格式错误"});
                    return; 
                }
                for(let i=0;i<ext.length;i++){
                    if(!Array.isArray(ext[i])){
                        rfun({view:"发送失败-格式错误"});
                        return; 
                    }
                }
            }catch(e){
                request.GET.query.E3 = null;
                rfun({view:"发送失败-格式错误"});
                return;
            }
            //console.log(request.GET.query);
            pubfun.DB.query("INSERT INTO mails(gametp,sendid,touserid,title,body,ext) VALUES(1,0,$1,$2,$3,$4)",(rs)=>{
                if(rs) rfun({view:"发送成功"}); 
                else rfun({view:"发送失败"}); 
            },[request.GET.query.V, request.GET.query.E1, request.GET.query.E2, request.GET.query.E3||null])
            return;
        }case "/ajax/chapter":{
			getData(request.GET.query, "SELECT userid,chapterid,title,ctp,createtime::text,pay,anum,rval,run,rsuccess,rfinish FROM cchapter", "createtime", rfun, true);
			return;
		}
    }
    rfun(dv);
}

/** 请求服务器 */
function getGameHttp(path, callback){
    const http = require("http");
    http.get("http://127.0.0.1:94/httpts?ac=reload&p=" + path, (res)=>{
        res.setEncoding('utf8');
        let rawData = '';
        res.on('data', (chunk) => { rawData += chunk; });
        res.on('end', () => {
            console.log("httpdata", rawData);
            callback(rawData);
        });
    })
}

/** 获取数据 */
function getData(query, sql, timestr, callback, isdb = false, isnick = false){
    const pubfun = require("../pubfun");
    let where = " WHERE 1 = 1 ", para = [];
    if(query.V){
        if(isnick){
            where += " AND (userid::text = $1 OR POSITION($1 IN nickname) > 0) ";
            para.push(query.V);
        }else{
            where += " AND userid = $1 ";
            para.push(query.V|0);
        }
    }
    if(query.B){
        where += " AND " + timestr + " > $" + (para.length + 1) + " AND " + timestr + "::date <= $"  + (para.length + 2);
        para.push(query.B);
        para.push(query.E);
    }
    if(query.I){
        where += " AND itemid = $" + (para.length + 1);
        para.push(query.I|0);
    }
    let count = "SELECT COUNT(*) c FROM (" + sql + ") T "  + where;
    sql += where + " ORDER BY " + timestr + " desc LIMIT 100 OFFSET " + (((query.P || 1) - 1) * 100);
    if(isdb){
        pubfun.DB.query(count, (rsc)=>{
            let dv = {total:rsc.rows[0].c};
            pubfun.DB.query(sql, (rs)=>{
                dv.data = rs.rows;
                callback(dv);
            },para,true);
        }, para);
    }else{
        pubfun.DB.queryLog(count, (rsc)=>{
            let dv = {total:rsc.rows[0].c};
            pubfun.DB.queryLog(sql, (rs)=>{
                dv.data = rs.rows;
                callback(dv);
            },para,true);
        }, para);
    }
}